package com.farm.wfs.service.impl;

import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.time.TimeTool;
import com.farm.util.web.FarmFormatUnits;
import com.farm.wfs.dao.DirTypeDaoInter;
import com.farm.wfs.domain.DirType;
import com.farm.wfs.service.DirTypeServiceInter;
import com.farm.wfs.service.WfileServiceInter;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：专题服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class DirTypeServiceImpl implements DirTypeServiceInter {

	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(DirTypeServiceImpl.class);
	@Resource
	private DirTypeDaoInter dirTypeDaoImpl;
	@Resource
	private WfileServiceInter wFileServiceImpl;

	@Override
	@Transactional
	public List<DirType> getAllDirs(String userid) {
		List<DirType> backTypes = new ArrayList<>();
		{
			// 構造用戶私有庫目錄
			DirType privateRootType = new DirType();
			privateRootType.setId("NONE");
			privateRootType.setName("我的网盘");
			privateRootType.setParentid("00000000000000000000000000000000");
			privateRootType.setTreecode("");
			backTypes.add(privateRootType);
		}
		List<DirType> types = dirTypeDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("CUSER", userid, "=")).add(new DBRule("PSTATE", "1", "=")).toList());
		Collections.sort(types, new Comparator<DirType>() {
			@Override
			public int compare(DirType type1, DirType type2) {
				return type1.getName().compareTo(type2.getName());
			}
		});
		for (DirType type : types) {
			DirType brief = new DirType();
			brief.setId(type.getId());
			brief.setName(type.getName());
			brief.setParentid(type.getParentid());
			brief.setTreecode(type.getTreecode());
			backTypes.add(brief);
		}
		return backTypes;
	}

	@Override
	@Transactional
	public List<DirType> getTypeAllParent(List<DirType> alltypes, String typeid) {
		List<DirType> backTypes = new ArrayList<>();
		if (StringUtils.isBlank(typeid)) {
			return backTypes;
		}
		String treecode = null;
		Map<String, DirType> alltypeMap = new HashMap<String, DirType>();
		for (DirType type : alltypes) {
			if (type.getId().equals(typeid)) {
				treecode = type.getTreecode();
			}
			alltypeMap.put(type.getId(), type);
		}
		for (String typid : FarmFormatUnits.getStrList(treecode, 32)) {
			backTypes.add(alltypeMap.get(typid));
		}
		return backTypes;
	}

	@Override
	@Transactional
	public DirType getDir(String userid, String typeid) {
		DirType type = dirTypeDaoImpl.getEntity(typeid);
		return type;
	}

	@Override
	@Transactional
	public DirType editDir(String typeid, String name, int sort, LoginUser currentUser) {
		DirType type = dirTypeDaoImpl.getEntity(typeid);
		type.setName(name);
		type.setSort(sort);
		dirTypeDaoImpl.editEntity(type);
		return type;
	}

	@Override
	@Transactional
	public void delDir(String typeid, LoginUser currentUser) {
		DirType type = dirTypeDaoImpl.getEntity(typeid);
		if (dirTypeDaoImpl.isHasChildNode(typeid)) {
			throw new RuntimeException("分类下存在子分类，无法删除!");
		}

		if (wFileServiceImpl.getFiles(typeid, currentUser.getId()).size() > 0) {
			throw new RuntimeException("分类下存在文件，无法删除!");
		}
		dirTypeDaoImpl.deleteEntity(type);
	}

	@Override
	@Transactional
	public void moveType(String userid, String typeid, String otypeid) {
		// 1.判断参数有消息
		if (StringUtils.isBlank(typeid) || StringUtils.isBlank(otypeid)) {
			throw new RuntimeException("typeid or destTypeid can't is null!");
		}
		// 2.判断目的分类是否为该分类的子分类
		DirType destType = getDir(userid, otypeid);
		if (otypeid.equals("NONE")) {
			destType = new DirType();
			destType.setName("我的网盘");
			destType.setId("NONE");
			destType.setTreecode("");
		}
		DirType type = getDir(userid, typeid);
		// 原来的treecode
		String originalTreecode = type.getTreecode();
		String raplaceTreecode = destType.getId().equals("NONE") ? type.getId()
				: (destType.getTreecode() + type.getId());
		if (destType == null || type == null) {
			throw new RuntimeException("type or destType can't is null!");
		}
		if (destType.getTreecode().indexOf(type.getId()) >= 0) {
			throw new RuntimeException("分类不能移动到其子类中!");
		}
		// 3.判斷目的分类是否为当前分类的父分类（不变）
		if (type.getParentid().equals(otypeid)) {
			// return;
		}
		// 4.把该分类的上级分类指向目的分类
		// 先查询，不然修改原分类后treecode对不上
		List<DirType> childTypes = dirTypeDaoImpl.allSubType(typeid);
		{
			type.setParentid(destType.getId());
			// type.setTreecode(destType.getTreecode() + type.getId());
			dirTypeDaoImpl.editEntity(type);
		}
		// 5.初始化该分类的所有子分类的treecode
		for (DirType node : childTypes) {
			// System.out.println(node.getName());
			// System.out.println(node.getTreecode());
			node.setTreecode(node.getTreecode().replace(originalTreecode, raplaceTreecode));
			dirTypeDaoImpl.editEntity(node);
		}
	}

	@Override
	@Transactional
	public List<DirType> getDirs(String dirid, String userid) {
		List<DirType> types = dirTypeDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("PARENTID", dirid, "=")).add(new DBRule("CUSER", userid, "=")).toList());
		Collections.sort(types, new Comparator<DirType>() {
			@Override
			public int compare(DirType type1, DirType type2) {
				return type1.getName().compareTo(type2.getName());
			}
		});
		return types;
	}

	@Override
	@Transactional
	public DirType createDir(String name, int sort, String parentId, LoginUser currentUser) {
		DirType type = new DirType();
		type.setCtime(TimeTool.getTimeDate14());
		type.setCuser(currentUser.getId());
		type.setCusername(currentUser.getName());
		type.setEtime(TimeTool.getTimeDate14());
		type.setName(name);
		type.setDirsize(0l);
		if (StringUtils.isBlank(parentId)) {
			parentId = "NONE";
		}
		type.setParentid(parentId);
		type.setPstate("1");
		type.setSort(sort);
		type.setTreecode("NONE");
		type = dirTypeDaoImpl.insertEntity(type);
		if (type.getParentid().equals("NONE")) {
			type.setTreecode(type.getId());
		} else {
			type.setTreecode(dirTypeDaoImpl.getEntity(type.getParentid()).getTreecode() + type.getId());
		}
		dirTypeDaoImpl.editEntity(type);
		return type;
	}

	@Override
	@Transactional
	public List<DirType> getDirPath(String dirid) {
		List<DirType> path = new ArrayList<>();
		DirType base = new DirType();
		base.setId("NONE");
		base.setName("我的网盘");
		path.add(base);
		if ("NONE".equals(dirid)) {
			return path;
		}
		DirType cdir = dirTypeDaoImpl.getEntity(dirid);
		if (cdir != null) {
			List<String> ids = FarmFormatUnits.SplitStringByLen(cdir.getTreecode(), 32);
			for (String id : ids) {
				path.add(dirTypeDaoImpl.getEntity(id));
			}
		}
		return path;
	}

	@Override
	@Transactional
	public List<DirType> searchDirs(String word, String userid) {
		return dirTypeDaoImpl.selectEntitys(DBRuleList.getInstance().add(new DBRule("NAME", word, "like"))
				.add(new DBRule("CUSER", userid, "=")).toList(), 100);
	}
}
